#include "server/websocket_server.hpp"

#include <filesystem>
#include <fstream>

[[noreturn]] void socket_server_test() {
    socket_server s(1234);
    win::socket sock;
    s.register_accept_hooks([&](win::socket socket, const win::sockaddr_in&) { sock = socket; });

    s.start();

    std::string cmd;
    cmd += 1;
    while (true) {
        std::cin >> cmd;
        if (!s.send(sock, std::vector(cmd.data(), cmd.data() + cmd.length()))) {
            std::cout << win::get_last_error_message() << std::endl;
        }
    }
}

int main(int, char**) {
    logger::get_instance().set_output_file_path("./log/server");
    websocket_server s(1234);
    win::socket sock;
    s.register_accept_hook([&](const websocket_connection& conn) { sock = conn.sock; });
    s.register_recv_hook([&](win::socket, const win::sockaddr_in& address, websocket_frame frame) {
        linfo("received websocket data from: " << nonstd::to_string(address) << "\n" << frame.description());

        if (frame.opcode == BINARY_FRAME) {
            auto file = "recv/" + std::to_string(now_in_i64()) + ".out";
            linfo("writing binary frame to " << file);
            if (!std::filesystem::exists("recv")) {
                std::filesystem::create_directory("recv");
            }
            std::ofstream fout(file, std::ios::out | std::ios::app | std::ios::binary);
            fout.write(frame.buffer.data(), frame.buffer.size());
        }
    });
    s.start();
    while (true) {
        std::string str;
        std::cin >> str;
        if (str == "close") {
            s.stop();
            break;
        }
        if (!s.send(sock, std::vector(str.begin(), str.end()), TEXT_FRAME)) {
            lwarn("send data to socket " << sock << " failed.");
        }
    }
    return 0;
}